package com.fly.reload;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.stereotype.Component;

/**
 * 
 * SpringConfig 监听器
 * 
 * @author 00fly
 * @version [版本号, 2018年7月20日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
@RefreshScope
public class ConfigMonitor
{
    static final Logger LOGGER = LoggerFactory.getLogger(ConfigMonitor.class);
    
    @Autowired
    ContextRefresher contextRefresher;
    
    public ConfigMonitor()
    {
        super();
        monitorStart();
    }
    
    /**
     * 开始监听
     * 
     * @see [类、类#方法、类#成员]
     */
    public void monitorStart()
    {
        try
        {
            File directory = new File("src/main/resources/");
            FileAlterationObserver observer = new FileAlterationObserver(directory, FileFilterUtils.suffixFileFilter(".properties"));
            observer.addListener(new FileAlterationListenerAdaptor()
            {
                @Override
                public void onFileChange(File file)
                {
                    LOGGER.info("{} changed.", file.getName());
                    contextRefresher.refresh();
                }
                
                @Override
                public void onFileCreate(File file)
                {
                    LOGGER.info("{} created.", file.getName());
                    contextRefresher.refresh();
                }
            });
            long interval = TimeUnit.SECONDS.toMillis(5); // 周期5秒
            FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
            monitor.start();
        }
        catch (Exception e)
        {
            LOGGER.error(e.getMessage(), e);
        }
    }
}